package com.github.bitsapling.sapling.controller;

import cn.dev33.satoken.annotation.SaCheckPermission;
import cn.dev33.satoken.stp.StpUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.github.bitsapling.sapling.entity.Comment;
import com.github.bitsapling.sapling.entity.Post;
import com.github.bitsapling.sapling.entity.Thumbup;
import com.github.bitsapling.sapling.entity.User;
import com.github.bitsapling.sapling.service.CommentService;
import com.github.bitsapling.sapling.service.PostService;
import com.github.bitsapling.sapling.service.ThumbupService;
import com.github.bitsapling.sapling.service.UserService;
import com.github.bitsapling.sapling.utils.DataConverter;
import jakarta.annotation.Resource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.sql.Timestamp;
import java.text.SimpleDateFormat;
import java.time.Instant;
import java.time.LocalDateTime;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 论坛控制器
 * 处理与论坛相关的API请求，适配前端API调用
 */
@RestController
@RequestMapping("/forum")
public class ForumController {
    @Resource
    private PostService postService;

    @Resource
    private UserService userService;

    @Autowired
    private CommentService commentService;

    @Autowired
    private ThumbupService thumbupService;


    /**
     * 获取论坛帖子列表
     *
     * @param page 页码，默认为1
     * @param limit 每页数量，默认为10
     * @param category 分类，可选
     * @return 帖子列表及分页信息
     */
    @GetMapping
    public Map<String, Object> getAllPosts(
            @RequestParam(defaultValue = "1") Integer page,
            @RequestParam(defaultValue = "10") Integer limit,
            @RequestParam(required = false) String category) {

        User user = userService.getUserById(StpUtil.getLoginIdAsLong());
        // 创建分页对象，注意页码从1开始，需要转换为从0开始
        Page<Post> pageParam = new Page<>(page, limit);

        // 构建查询条件
        QueryWrapper<Post> queryWrapper = new QueryWrapper<>();


        // 按创建时间降序排序
        queryWrapper.orderByDesc("created_time");

        // 执行分页查询
        Page<Post> postPage = postService.page(pageParam, queryWrapper);

        // 获取帖子列表
        List<Post> posts = postPage.getRecords();

        // 获取所有帖子ID
        List<Long> postsIds = posts.stream().map(Post::getId).toList();

        // 获取帖子的评论数量
        Map<Long, Long> commentCountMap = getCommentCountByNoteIds(postsIds);

        // 获取帖子的点赞数量
        Map<Long, Long> likeCountMap = getLikeCountByNoteIds(postsIds);

        // 转换为前端期望的格式
        List<Map<String, Object>> notes = posts.stream()
                .map(post -> {
                    Map<String, Object> note = DataConverter.convertNoteToPost(post);

                    // 添加评论数量
                    Long commentCount = commentCountMap.getOrDefault(post.getId(), 0L);
                    note.put("comments", commentCount);

                    // 添加点赞数量
                    Long likeCount = likeCountMap.getOrDefault(post.getId(), 0L);
                    note.put("likes", likeCount);

                    return note;
                })
                .toList();

        // 构建返回结果
        Map<String, Object> result = new HashMap<>();
        result.put("posts", posts);
        result.put("total", postPage.getTotal());
        result.put("page", page);
        result.put("limit", limit);

        return result;
    }

    /**
     * 获取单个帖子详情
     *
     * @param id 帖子ID
     * @return 帖子详情，包括评论
     */
    @GetMapping("/{id}")
    public Map<String, Object> getPostById(@PathVariable Long id) {
        User user = userService.getUserById(StpUtil.getLoginIdAsLong());
        // 获取帖子
        Post post = postService.getById(id);

        // 如果帖子不存在，返回404
        if (post == null) {
            Map<String, Object> error = new HashMap<>();
            error.put("error", "帖子不存在");
            return error;
        }

        // 获取帖子评论
        List<Comment> comments = getCommentsByNoteId(id);

        // 获取帖子点赞数量
        long likeCount = getLikeCountByNoteId(id);

        // 转换为前端期望的格式
        Map<String, Object> note = DataConverter.convertNoteToPost(post);

        // 添加评论
        List<Map<String, Object>> commentsList = comments.stream()
                .map(DataConverter::convertCommentToFrontend)
                .collect(Collectors.toList());

        note.put("comments", commentsList);
        note.put("likes", likeCount);

        return note;
    }

    /**
     * 创建新帖子
     *
     * @param postData 帖子数据
     * @return 创建结果
     */
    @PostMapping
    public Map<String, Object> createPost(@RequestBody Map<String, Object> postData) {
        User user = userService.getUserById(StpUtil.getLoginIdAsLong());
        // 从请求体中获取帖子数据
        String title = (String) postData.get("title");
        String content = (String) postData.get("content");
        String category = (String) postData.get("category");

        // 验证必要字段
        if (title == null || content == null) {
            Map<String, Object> error = new HashMap<>();
            error.put("error", "标题和内容不能为空");
            return error;
        }

        // 创建帖子对象
        Post note = new Post();
        note.setTitle(title);
        note.setContent(content);


        // 设置创建时间
        note.setCreateTime(Timestamp.from(Instant.now()).toLocalDateTime());

        // 设置创建者（这里假设为1，实际应该从认证信息中获取）
        note.setUserId(user.getId());
        note.setCreatedBy(user.getUsername());

        // 设置分类（这里假设为1，实际应该根据前端传递的分类ID）
        note.setForumId(1L);

        // 设置是否置顶
        note.setIsPinned(0);

        // 保存帖子
        boolean success = postService.save(note);

        // 构建返回结果
        Map<String, Object> result = new HashMap<>();
        if (success) {
            result.put("success", true);
            result.put("id", note.getId());
            result.put("message", "帖子创建成功");
        } else {
            result.put("success", false);
            result.put("message", "帖子创建失败");
        }

        return result;
    }

    /**
     * 添加帖子评论
     *
     * @param id 帖子ID
     * @param commentData 评论数据
     * @return 评论结果
     */
    @PostMapping("/{id}/comments")
    public Map<String, Object> addComment(@PathVariable Long id, @RequestBody Map<String, String> commentData) {
        User user = userService.getUserById(StpUtil.getLoginIdAsLong());
        // 检查帖子是否存在
        Post post = postService.getById(id);
        if (post == null) {
            Map<String, Object> error = new HashMap<>();
            error.put("error", "帖子不存在");
            return error;
        }

        // 从请求体中获取评论内容
        String content = commentData.get("content");

        // 验证评论内容
        if (content == null || content.isEmpty()) {
            Map<String, Object> error = new HashMap<>();
            error.put("error", "评论内容不能为空");
            return error;
        }

        // 创建评论对象
        Comment comment = new Comment();
        comment.setPostId(id);
        comment.setContent(content);

        // 设置用户ID
        comment.setUserId(user.getId());
        comment.setCreatedBy(user.getUsername());

        // 设置创建时间
        comment.setCreatedTime(Timestamp.from(Instant.now()).toLocalDateTime());

        // 保存评论
        boolean success = commentService.save(comment);

        // 构建返回结果
        Map<String, Object> result = new HashMap<>();
        if (success) {
            result.put("success", true);
            result.put("id", comment.getId());
            result.put("message", "评论发布成功");

            // 添加评论详情
            result.put("comment", DataConverter.convertCommentToFrontend(comment));
        } else {
            result.put("success", false);
            result.put("message", "评论发布失败");
        }

        return result;
    }
    /**
     * 删除帖子
     *
     * @param id 帖子ID
     * */
    @PostMapping("/{id}/delete")
    @SaCheckPermission(value = "torrent:review", orRole = "admin")
    public Map<String, Object> deletePost(@PathVariable Long id) {
        // 检查帖子是否存在
        Post note = postService.getById(id);
        if (note == null) {
            Map<String, Object> error = new HashMap<>();
            error.put("error", "帖子不存在");
            return error;
        }

        boolean success=postService.determinePost(note);
        Map<String, Object> result = new HashMap<>();
        if (success) {
            result.put("success", "删除成功");
            return result;
        }
        result.put("false", "删除操作失败");
        return result;
    }

    /**
     * 删除评论
     *
     * @param id 评论id
     * */
    @PostMapping("/{id}/comment/delete")
    @SaCheckPermission(value = "torrent:review", orRole = "admin")
    public Map<String, Object> deleteComment(@PathVariable Long id) {
        // 检查帖子是否存在
        Comment comment = commentService.getById(id);
        if (comment == null) {
            Map<String, Object> error = new HashMap<>();
            error.put("error", "评论不存在");
            return error;
        }

        boolean success=commentService.determinePost(comment);
        Map<String, Object> result = new HashMap<>();
        if (success) {
            result.put("success", "删除成功");
            return result;
        }
        result.put("false", "删除操作失败");
        return result;
    }


    /**
     * 点赞帖子
     *
     * @param id 帖子ID
     * @return 点赞结果
     */
    @PostMapping("/{id}/like")
    public Map<String, Object> likePost(@PathVariable Long id) {
        // 检查帖子是否存在
        Post note = postService.getById(id);
        if (note == null) {
            Map<String, Object> error = new HashMap<>();
            error.put("error", "帖子不存在");
            return error;
        }

        // 假设当前用户ID为1，实际应该从认证信息中获取
        User user = userService.getUserById(StpUtil.getLoginIdAsLong());

        // 检查用户是否已经点赞
        QueryWrapper<Thumbup> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("note_id", id);
        queryWrapper.eq("user_id", user.getId());

        Thumbup existingLike = thumbupService.getOne(queryWrapper);

        Map<String, Object> result = new HashMap<>();

        if (existingLike != null) {
            // 如果已经点赞，则取消点赞
            boolean success = thumbupService.removeById(existingLike.getId());

            if (success) {
                result.put("success", true);
                result.put("liked", false);
                result.put("message", "取消点赞成功");
            } else {
                result.put("success", false);
                result.put("message", "取消点赞失败");
            }
        } else {
            // 如果未点赞，则添加点赞
            Thumbup thumbup = new Thumbup();
            thumbup.setNoteId(id);
            thumbup.setUserId(user.getId());
            thumbup.setCreateTime(Timestamp.from(Instant.now()).toLocalDateTime());

            boolean success = thumbupService.save(thumbup);

            if (success) {
                result.put("success", true);
                result.put("liked", true);
                result.put("message", "点赞成功");
            } else {
                result.put("success", false);
                result.put("message", "点赞失败");
            }
        }

        // 获取最新点赞数量
        long likeCount = getLikeCountByNoteId(id);
        result.put("likeCount", likeCount);

        return result;
    }

    /**
     * 获取帖子的评论列表
     *
     * @param noteId 帖子ID
     * @return 评论列表
     */
    private List<Comment> getCommentsByNoteId(Long noteId) {
        QueryWrapper<Comment> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq(" post_id", noteId);
        queryWrapper.orderByDesc("created_time");

        return commentService.list(queryWrapper);
    }

    /**
     * 获取帖子的点赞数量
     *
     * @param noteId 帖子ID
     * @return 点赞数量
     */
    private long getLikeCountByNoteId(Long noteId) {
        QueryWrapper<Thumbup> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("note_id", noteId);

        return thumbupService.count(queryWrapper);
    }

    /**
     * 批量获取帖子的评论数量
     *
     * @param noteIds 帖子ID列表
     * @return 帖子ID到评论数量的映射
     */
    private Map<Long, Long> getCommentCountByNoteIds(List<Long> noteIds) {
        if (noteIds.isEmpty()) {
            return Collections.emptyMap();
        }

        QueryWrapper<Comment> queryWrapper = new QueryWrapper<>();
        queryWrapper.in("post_id", noteIds);

        List<Comment> comments = commentService.list(queryWrapper);

        // 统计每个帖子的评论数量
        Map<Long, Long> commentCountMap = new HashMap<>();
        for (Comment comment : comments) {
            Long noteId = comment.getPostId();
            commentCountMap.put(noteId, commentCountMap.getOrDefault(noteId, 0L) + 1);
        }

        return commentCountMap;
    }

    /**
     * 批量获取帖子的点赞数量
     *
     * @param noteIds 帖子ID列表
     * @return 帖子ID到点赞数量的映射
     */
    private Map<Long, Long> getLikeCountByNoteIds(List<Long> noteIds) {
        if (noteIds.isEmpty()) {
            return Collections.emptyMap();
        }

        QueryWrapper<Thumbup> queryWrapper = new QueryWrapper<>();
        queryWrapper.in("note_id", noteIds);

        List<Thumbup> likes = thumbupService.list(queryWrapper);

        // 统计每个帖子的点赞数量
        Map<Long, Long> likeCountMap = new HashMap<>();
        for (Thumbup like : likes) {
            Long noteId = like.getNoteId();
            likeCountMap.put(noteId, likeCountMap.getOrDefault(noteId, 0L) + 1);
        }

        return likeCountMap;
    }
}

